#include "serialportsetdlg.h"
#include "ui_serialportsetdlg.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include <QMessageBox>
#include <QCloseEvent>

#define KNXCOMTYPE "CH340"
#define BAUDRATE 38400

QSerialPort *serial;
static int widgetFlag = 1;

SerialPortSetDlg::SerialPortSetDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SerialPortSetDlg)
{
    ui->setupUi(this);
    
    ui->closeCompushButton->setEnabled(false);
    
    connect(ui->autoSearchComcheckBox, SIGNAL(clicked(bool)), this, SLOT(searchSerialPort(bool)));
    connect(ui->autoOpenComcheckBox, SIGNAL(clicked(bool)), this, SLOT(openKNXSerialPort(bool)));
    connect(ui->closeCompushButton, SIGNAL(clicked(bool)), this, SLOT(closeSerialPort()));
    connect(ui->openComButton, SIGNAL(clicked(bool)), this, SLOT(setAndOpenSerialPort()));
}

SerialPortSetDlg::~SerialPortSetDlg()
{
    closeEvent(0);
    delete ui;
}

void SerialPortSetDlg::closeEvent(QCloseEvent *event)
{
    if(!widgetFlag)
    {
        event->ignore();  //忽略关闭事件
        QMessageBox::warning(this,"警告","未关闭串口，不得退出该窗口");
    }
}

void SerialPortSetDlg::openKNXSerialPort(bool checked)
{
    if(!checked)
        return;
    
    //获取comboBox的个数
    int comNum = ui->portBox->count();
    qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"搜索到的串口个数:"<<comNum;
    
    //获取comboBox中的数据并比对是否是我们的串口芯片
    for(int i = 0;i < comNum;i++)
    {
        QString data = ui->portBox->itemText(i);
        if(data.contains(KNXCOMTYPE))
        {
            //将comboBox的默认值设为该串口
            ui->portBox->setCurrentIndex(i);
            setAndOpenSerialPort();
            qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"打开knx串口成功";
        }
    }
}

void SerialPortSetDlg::setAndOpenSerialPort()
{
    serial = new QSerialPort;
    QString portTmp = ui->portBox->currentText();
    int siteBegin = portTmp.indexOf("(");
    int siteEnd = portTmp.indexOf(")");
    int size = siteEnd - siteBegin - 1;
    QString portName = portTmp.mid(siteBegin + 1, size);
    
    qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"开启位置:"<<siteBegin
           <<"结束位置:"<<siteEnd<<"串口号长度:"<<size<<"串口名:"<<portName;
    serial->setPortName(portName);
    if(!serial->open(QIODevice::ReadWrite))
    {
        qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"打开串口失败："<<serial->errorString();
        QMessageBox::warning(this, "提示信息", QString(serial->errorString()).append(serial->portName()));
        return;
    }
    widgetFlag = 0;  //只要打开了串口就不能关闭该窗口
    
    //如果打开的不是knx串口finished信号传递值为2，是则传递值为1，关闭时传递0
    QString data = ui->portBox->currentText();
    if(data.contains(KNXCOMTYPE))
        this->finished(1);
    else
        this->finished(2);
    
    serial->setBaudRate(BAUDRATE);
    serial->setDataBits(QSerialPort::Data8);
    serial->setParity(QSerialPort::NoParity);
    serial->setStopBits(QSerialPort::OneStop);
    serial->setFlowControl(QSerialPort::NoFlowControl);
    serial->setReadBufferSize(0);
    
    ui->portBox->setEnabled(false);
    ui->openComButton->setEnabled(false);
    ui->closeCompushButton->setEnabled(true);
    ui->autoOpenComcheckBox->setEnabled(false);
}

void SerialPortSetDlg::searchSerialPort(bool checked)
{
    if(!checked)
        return;
        
    ui->portBox->clear();
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        QSerialPort serialTmp;
        serialTmp.setPort(info);
        ui->portBox->addItem(QString(info.description()).append("(").append(info.portName()).append(")"));
        if(serialTmp.open(QIODevice::ReadWrite))
        {
            serialTmp.close();
        }
        else
        {
            qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"串口打开失败，或串口已打开";
            QMessageBox::warning(this, "提示信息", QString("串口打开失败，串口已打开：%1").arg(info.portName()));
        }
    }
}

void SerialPortSetDlg::closeSerialPort()
{
    serial->clearError();
    serial->clear();
    serial->close();
    qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__<<"关闭串口完成";
    ui->portBox->setEnabled(true);
    ui->openComButton->setEnabled(true);
    widgetFlag = 1;
    ui->closeCompushButton->setEnabled(false);
    ui->autoOpenComcheckBox->setEnabled(true);
    this->finished(0);
}
